/**
 * 获取m-n之间的随机数
 * @param {*} m
 * @param {*} n
 * @returns
 */
function getRandom(m, n) {
	var max = Math.max(m, n)
	var min = Math.min(m, n)
	return Math.floor(Math.random() * (max - min) + min)
}

/**
 * 格式化当前日期时间
 *  yyyy年MM月dd日 时:分：秒
 */
function formatCurrentDate() {
	var data = new Date()
	var str = `${data.getFullYear()}年${
		data.getMonth() + 1
	}月${data.getDate()}日 ${data.getHours()}时:${data.getMinutes()}分:${data.getSeconds()}秒`
	return str
}
/**
 * EventUtil: 事件工具对象
 */
let EventUtil = {
	//事件对象
	getEvent: function (e) {
		return (e = e || window.event)
	},
	//事件目标对象
	getTarget: function (e) {
		var e = this.getEvent(e)
		return e.target || e.srcElement
	},
	//键盘键码
	getKeyCode: function (e) {
		var e = this.getEvent(e)
		return e.keyCode || e.which
	},
	//阻止事件传播
	stopPropagation: function (e) {
		var e = this.getEvent(e)
		e.stopPropagation ? e.stopPropagation() : (e.cancelBubble = true)
	},
}
// ajax封装2.0
function ajax(options) {
	const xhr = new window.XMLHttpRequest()
	let method = options.method.toUpperCase()
	if (method == 'GET') {
		let params = changeObjParme(options.data)
		xhr.open(method, options.url + '?' + params)
		xhr.send()
	} else if (method == 'POST') {
		xhr.open(method, options.url)
		xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
		let params = changeObjParme(options.data)
		xhr.send(params)
	}

	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				let data = JSON.parse(xhr.responseText)
				options.success(data)
			} else {
				options.error('请求出错')
			}
		}
	}
}
/*
        {
            username:'admin',
            password:123
        }
        username='admin'&password=123
        遍历对象, 转属性为属性名=属性值形式， 再拼接起来
     -->
	 */
function changeObjParme(obj) {
	let arr = [] //[username='admin', password=123]
	for (let key in obj) {
		let params = `${key}=${obj[key]}`
		console.log(params);
		arr.push(params)
	}
	let line = arr.join('&') //username='admin'&password=123

	return line
}
// options登录3.0
function myPromise(options) {
	//1.创建promise,封装异步任务
	let promise = new Promise(function (resolve, reject) {
		// 2. 封装ajax异步任务
		const xhr = new window.XMLHttpRequest()
		let method = options.method.toUpperCase()
		if (method == 'GET') {
			let params = changeObjParme(options.data)
			xhr.open(method, options.url + '?' + params)
			xhr.send()
		} else if (method == 'POST') {
			xhr.open(method, options.url)
			xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
			let params = changeObjParme(options.data)
			xhr.send(params)
		}

		xhr.onreadystatechange = function () {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					let data = JSON.parse(xhr.responseText)
					resolve(data) //resolve成功状态
				} else {
					reject('请求出错 '+xhr.status) //reject失败状态
				}
			}
		}
	})
	return promise
}

